package com.chs.recoginition.core.handler;

import com.chs.recoginition.core.exception.constant.ExceptionConstant;
import com.chs.recoginition.core.utils.JsonUtils;
import com.chs.recoginition.vo.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ForbiddenHandler implements AccessDeniedHandler {

    /**
     * 没有权限 403 时触发的操作，提示没有权限
     */
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        // 返回json形式的错误信息
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);

        httpServletResponse.getWriter().println(JsonUtils.toJson(Result.error(ExceptionConstant.BEYOND_THE_PERMISSIONS)));
        httpServletResponse.getWriter().flush();
    }
}